import React, { createRef, PureComponent } from 'react'
import {
  Select, DatePicker, message,
} from 'antd'
import { connect, history } from '@umijs/max'
import moment from 'moment'
import _ from 'lodash'
import {
  InputSearch, Logger, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import Tools from '@/utils/Tools'
import styles from './index.less'

const Bus = Tools.Bus

const { Option } = Select
const { OperateItem } = ProTableOperate
const { RangePicker } = DatePicker

const statusEnum = [
  // {
  //   text: '待发布', value: 1, icon: 'icon-daiban', color: 'hu-blue',
  // },
  // {
  //   text: '已发布', value: 2, icon: 'icon-yifabu', color: 'hu-green',
  // },
  {
    text: '未运行', value: 3, icon: 'icon-weiyunhang', color: 'hu-blue',
  },
  {
    text: '运行中', value: 4, icon: 'icon-yunhangzhong_1', color: 'hu-blue',
  },
  {
    text: '成功', value: 5, icon: 'icon-chenggong', color: 'hu-green',
  },
  {
    text: '失败', value: 6, icon: 'icon-shibai1', color: 'hu-red',
  },
  {
    text: '停止', value: 7, icon: 'icon-weiyunhang', color: 'hu-blue',
  },
  {
    text: '已归档', value: 8, icon: 'icon-guidang', color: 'hu-blue',
  },
]

@connect(({ offlineOperation }) => ({ ...offlineOperation }))
class History extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      filter_taskStatus: this.props?.filteredDefaultValue || [],
      filter_executeType: [], // 从概览页的失败数、成功数跳转到任务运行记录页，调度类型筛选都为 周期执行
      query: {
        // nodeName: this.props?.searchValue || '',
        taskStatus: this.props?.filteredDefaultValue?.[0] || '',
        taskId: this.props?.searchValue || '', // 注意一个问题，从历史任务跳转过来后，在本页面所有搜索都会带上 taskId 这个参数 （已与后端、测试确认过）
        // executeType: this.props?.filteredDefaultValue?.[0] ? 0 : '', // 从概览页的失败数、成功数跳转到任务运行记录页，调度类型筛选都为 周期执行
        executeType: '',
      },
      forceUpdateKey: 0,
      expandedRowKeys: [],
      loading: false,
      userList: [],
      optTypeParams: null,
      loggerList: [],
      // nodeName: this.props?.searchValue || '',
      nodeName: '',
    }
    this.tableRef = createRef()
    this.logger = createRef()
  }

  componentDidMount() {
    this.queryUserList()
  }

  getColumn = () => (
    [
      {
        title: '任务名称',
        key: 'taskName',
        width: '17%',
        render: (record) => (
          <span className={styles.link} onClick={() => { history.push(`/dataIntegrate/offline-detail?id=${record.offlineSyncId}`) }}>{record?.taskName}</span>
        ),
      },
      {
        title: '任务状态',
        dataIndex: 'taskStatus',
        key: 'taskStatus',
        width: '9%',
        filters: statusEnum,
        filteredValue: this.state.filter_taskStatus,
        // defaultFilteredValue: this.props?.filteredDefaultValue || [],
        // onFilter: (value, record) => record.taskStatus === value,
        render: (status) => {
          const statusEnumObj = statusEnum.filter(item => item.value === status)?.[0] || {}
          return (
            _.isEmpty(statusEnumObj) ? '-' : <><i className={`iconfont ${statusEnumObj.icon} ${statusEnumObj.color}`} /> {statusEnumObj.text} </>
          )
        },
      },
      {
        title: '调度类型',
        dataIndex: 'executeType',
        key: 'executeType',
        width: '8%',
        filters: [
          { text: '手工执行', value: 1 },
          { text: '周期执行', value: 0 },
        ],
        // onFilter: (value, record) => record.executeType === value,
        filteredValue: this.state.filter_executeType,
        render: (executeType) => (
          <>
            {executeType === 1 && '手工执行'}
            {executeType === 0 && '周期执行'}
          </>
        ),
      },
      {
        title: '计划开始时间',
        dataIndex: 'planTime',
        key: 'planTime',
        width: '13%',
        sorter: true,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '启动时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: '13%',
        sorter: true,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
        width: '13%',
        sorter: true,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '运行时长(S)',
        dataIndex: 'duration',
        key: 'duration',
        width: '9%',
        sorter: true,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '责任人',
        dataIndex: 'creator',
        key: 'creator',
        width: '8%',
      },
      {
        title: '操作',
        key: 'ignored',
        width: '10%',
        render: (record) => {
          const {
            id, taskStatus, offlineSyncId, ignored,
          } = record
          return (
            <ProTableOptions size={4}>
              <span onClick={() => {
                this.setState({
                  loggerList: [],
                })
                this.viewLog(id, this.state.offsets, false)
                Bus.emit('iconUpFn2')
              }}
              >
                查看日志
              </span>
              {
                (taskStatus !== 4 || null) && ( // 测试要求
                  <span onClick={() => {
                    this.reRun(offlineSyncId)
                  }}
                  >重跑
                  </span>
                )
              }
              {
                (taskStatus === 4 || null) && (
                  <span onClick={() => {
                    this.setState({
                      loggerList: [],
                    })
                    this.queryStop([id], null)
                  }}
                  >
                    终止运行
                  </span>
                )
              }
              {
                (ignored !== 1 && taskStatus !== 4) && (
                  <span onClick={() => {
                    this.setState({
                      loggerList: [],
                    })
                    this.queryIgnore([id])
                  }}
                  >
                    归档
                  </span>
                )
              }
              {
                (ignored === 1) && (
                  <span>
                    已归档
                  </span>
                )
              }
            </ProTableOptions>
          )
        },
      },
    ]
  )

  queryUserList = () => {
    this.props.dispatch({
      type: 'offlineOperation/queryUserList',
      cb: (res) => {
        this.setState({
          userList: res || [],
        })
      },
    })
  }

  fetchData = (isReset = true) => {
    const {
      userId = '', nodeName = '', endTime = '', startTime = '', query,
    } = this.state
    isReset && this.tableRef?.current?.resetPageNum()
    const tempQuery = {
      nodeName, startTime, endTime, userId,
    }
    this.setState({
      query: {
        ...query,
        ...tempQuery,
      },
    })
  }

  // 归档任务
  queryIgnore = (idsArr) => {
    let idsStr = ''
    idsArr.map((item) => {
      if (idsStr !== '') idsStr += ','
      idsStr += item
      return null
    })
    this.setState({
      loading: true,
    })
    this.props.dispatch({
      type: 'offlineOperation/queryIgnore',
      params: {
        ids: idsStr,
      },
      cb: (res) => {
        const { status, msg } = res || {}

        // 后端需要2s的延时执行
        setTimeout(() => {
          this.setState({
            optTypeParams: null,
            loading: false,
          })
          if (status === 200) {
            message.success('操作成功')
            this.forceUpdateFn()
          } else {
            message.error(msg || '系统异常，请稍后重试~')
          }
        }, 2000)
      },
    })
  }

  // 批量归档任务
  batchIgnore = (optTypeParams) => {
    const selectedRowKeys = this.tableRef?.current?.state?.selectedRowKeys
    if (selectedRowKeys.length < 1) {
      message.warning('请至少选择一条数据')
      return null
    }
    this.setState({
      optTypeParams,
      loading: true,
    })
    this.queryIgnore(selectedRowKeys)
  }

  // 批量停止任务
  queryStop = (idArr, optTypeParams) => {
    const selectedRowKeys = idArr?.length ? idArr : this.tableRef?.current?.state?.selectedRowKeys
    if (selectedRowKeys.length < 1) {
      message.warning('请至少选择一条数据')
      return null
    }
    let idsStr = ''
    selectedRowKeys.map((item) => {
      if (idsStr !== '') idsStr += ','
      idsStr += item
      return null
    })

    this.setState({
      optTypeParams,
      loading: true,
    })
    this.props.dispatch({
      type: 'offlineOperation/queryStop',
      params: {
        logIds: idsStr,
      },
      cb: (res) => {
        const { status, msg } = res || {}

        // 后端需要2s的延时执行
        setTimeout(() => {
          this.setState({
            optTypeParams: null,
            loading: false,
          })
          if (status === 200) {
            message.success('操作成功')
            this.forceUpdateFn()
          } else {
            message.error(msg || '系统异常，请稍后重试~')
          }
        }, 2000)
      },
    })
    return null
  };

  forceUpdateFn = () => {
    this.setState((prevSta) => ({
      forceUpdateKey: prevSta.forceUpdateKey + 1,
    }))
  }

  // 重跑
  reRun = (id, pid) => {
    this.setState({ loading: true })
    this.props.dispatch({
      type: 'offlineOperation/queryRestart',
      params: {
        taskId: id,
        runType: 0,
      },
      cb: (res) => {
        const { status, msg } = res || {}
        this.setState({
          loading: false,
        })
        if (status === 200) {
          message.success('操作成功')
          if (pid !== undefined) {
            // this.querySubTask(pid)
          } else {
            this.fetchData(false)
          }
        } else {
          message.error(msg || '系统异常，请稍后重试~')
        }
      },
    })
  }

  // 查看日志
  viewLog = (jobId, offsets, bool) => {
    clearInterval(this.time)
    this.setState({
      loading: true,
    })
    this.props.dispatch({
      type: 'offlineOperation/queryLog',
      params: {
        logId: jobId,
        offset: offsets || 0, // 参考老版本，传了固定值
      },
      cb: (res) => {
        const { status, msg, data } = res || {}
        this.setState({
          loading: false,
        })
        const domWrapper = document.querySelector('#layout_container_content')
        const currentScroll = domWrapper.scrollTop // 已经被卷掉的高度
        const scrollHeight = domWrapper.scrollHeight // 内容总高度
        domWrapper.scrollTo(0, (scrollHeight - currentScroll))

        if (status === 200) {
          this.setState((prevState) => ({
            loggerList: prevState.loggerList.concat(data?.logContent),
          }))
          this.time = setInterval(() => {
            if (data?.logEnd && bool) {
              // this.fetchData()
              clearInterval(this.time)
            } else if (data?.logEnd) {
              clearInterval(this.time)
            } else {
              this.viewLog(jobId, data?.offset, bool)
            }
          }, 4000)
        } else {
          message.error(msg || '系统异常，请稍后重试~')
        }
      },
    })
  }

  handleTableChange = (pagination, filters, sorter) => {
    console.log(filters)
    const queryFilter = {}
    for (const f in filters) {
      if (filters[f]) {
        queryFilter[f] = filters[f].join(',')
      }
      this.setState({ [`filter_${f}`]: filters[f] })
    }

    if (sorter?.order) {
      queryFilter.order = sorter?.order === 'descend' ? 'desc' : 'asc'
      queryFilter.orderField = sorter?.field
    }

    const {
      userId, nodeName, endTime, startTime,
    } = this.state
    this.tableRef?.current?.resetPageNum()

    const tempQuery = {}
    tempQuery.nodeName = nodeName || ''
    tempQuery.startTime = startTime || ''
    tempQuery.endTime = endTime || ''
    tempQuery.userId = userId || ''

    this.setState({
      query: {
        ...tempQuery,
        ...queryFilter,
      },
    })
  }

  render() {
    const {
      loading, query, expandedRowKeys, nodeName, userList, forceUpdateKey, optTypeParams, loggerList,
    } = this.state
    const rowSelection = {
      type: 'checkbox',
    }

    return (
      <div className={styles.history}>
        <div className={styles.page_content_column}>
          <div className={`${styles.page_content_right} ${styles.page_content_right_flex}`}>
            <ProTableOperate style={{ marginBottom: 12 }}>
              <OperateItem>
                <span>责任人</span>
                <Select
                  allowClear
                  onChange={(value) => {
                    this.setState({
                      userId: value || '',
                    }, () => {
                      this.logger.current.iconDownFn()
                      this.fetchData()
                    })
                  }}
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                >
                  {
                    userList?.map(item => (
                      <Option key={item.id} value={item.id}>{item.username}</Option>
                    ))
                  }
                </Select>
              </OperateItem>
              <OperateItem large_label>
                <span style={{ width: 100 }}>计划开始时间</span>
                <RangePicker
                  showTime
                  ranges={{
                    今天: [moment(), moment()],
                    最近7天: [moment().add(-7, 'd'), moment()],
                    最近30天: [moment().add(-30, 'd'), moment()],
                  }}
                  onChange={(date, dateStr) => {
                    this.setState({
                      startTime: dateStr[0],
                      endTime: dateStr[1],
                    }, () => {
                      this.logger.current.iconDownFn()
                      this.fetchData()
                    })
                  }}
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                />
              </OperateItem>
              <OperateItem align="left">
                <InputSearch
                  value={nodeName}
                  placeholder="请输入任务名称进行搜索"
                  onChange={(e) => {
                    this.setState({
                      nodeName: e.target.value,
                    })
                  }}
                  onSearch={() => {
                    this.logger.current.iconDownFn()
                    this.fetchData()
                  }}
                />
              </OperateItem>
            </ProTableOperate>

            <ProTable
              ref={this.tableRef}
              loading={loading}
              key={forceUpdateKey}
              url="/api/v1/integration/offline/operation/task/history"
              query={query}
              rowKey="id"
              // columns={columns}
              columns={this.getColumn()}
              expandedRowKeys={expandedRowKeys}
              resetExpandedRowKeys={this.resetExpandedRowKeys}
              rowSelection={rowSelection}
              onChange={this.handleTableChange}
              bulkOperation={[
                {
                  title: '批量杀任务',
                  loading: optTypeParams === 0 ? loading : false,
                  onClick: (params) => { this.queryStop(params, 0) },
                },
                {
                  title: '批量归档任务',
                  loading: optTypeParams === 0 ? loading : false,
                  onClick: (params) => { this.batchIgnore(0) },
                },
              ]}
            />
          </div>

          <Logger
            list={loggerList || []}
            ref={this.logger}
          />
        </div>
      </div>
    )
  }
}

export default History
